#ifndef SessionManager_h__
#define SessionManager_h__

#include "io_service_pool.h"
#include "IObject/ISessionManager.h"
#include "TCPSession.h"
#include "IObject/ILogger.h"

class SessionManager : public ISessionManager
{
public:
	SessionManager();
	~SessionManager();

public:
	void	Start(int threadCount,
		std::vector<boost::asio::ip::tcp::endpoint> & ips,
		std::vector<boost::asio::ip::tcp::endpoint> & https);

	void	StopAll();

	void	Close(SocketID sid);


	virtual SendResult AsyncSend(SocketID nSID, const char *pBuffer, int size, CONTENT_TYPE type);
	virtual SendResult SyncSend(SocketID nSID, const char *pBuffer, int size, CONTENT_TYPE type);

	virtual void BoradcastTo(const std::vector<SocketID> nSID, const char *pBuffer, int size, CONTENT_TYPE type);
	virtual void BoradcastToAll(const char *pBuffer, int size, CONTENT_TYPE type);

public:
	void check_socket(int expired_max);
private:
	void startTcp(const boost::asio::ip::tcp::endpoint & ep);

	void startHttp(const boost::asio::ip::tcp::endpoint & ep);

	void OnTcpAccept(const boost::system::error_code & e,
		boost::shared_ptr<boost::asio::ip::tcp::socket> pSocket,
		boost::shared_ptr<boost::asio::ip::tcp::acceptor> pAcceptor);

	void OnHttpAccept(const boost::system::error_code & e,
		boost::shared_ptr<boost::asio::ip::tcp::socket> pSocket,
		boost::shared_ptr<boost::asio::ip::tcp::acceptor> pAcceptor);

	void RealCloseSession(SocketID sid);
	void RealStop();

private:
	boost::asio::io_service& get_io_service();
protected:
	io_service_pool m_io_sockets;

	std::vector< boost::shared_ptr<boost::asio::ip::tcp::acceptor> > m_acceptors;
	std::map<SocketID, boost::shared_ptr<TCPSession> > m_SessionMap;

	SocketID							m_SocketIDGen;
	boost::asio::io_service				m_io;
	boost::asio::io_service::work		m_work;
	boost::shared_ptr<boost::thread>	m_thread;
	ILogger								*m_pLogger;
	boost::recursive_mutex				m_recursive_mutex;
};

#endif // SessionManager_h__
